import React, { useEffect, useState } from "react";
import {
  Pagination,
  Spin,
  Popconfirm,
  Button,
  message,
  Input,
  Modal,
} from "antd";
import { _categories, _delete, _add } from "./Api";
import "./Products_control.css";

const Products_control = () => {
  const [cateList, setCateList] = useState([]); //初始化分类数据state
  const [loading, setLoading] = useState(true); // 初始化加载状态
  const [current, setCurrent] = useState(1); //当前页
  const [isModalOpen, setIsModalOpen] = useState(false); //初始化提示框
  const [name, setName] = useState(); //新分类

  //渲染分类列表
  useEffect(() => {
    const cateReq = async () => {
      try {
        const res = await _categories([current, 4]);
        const cateList = await res[0];

        setCateList(cateList);
        setLoading(false);
      } catch (err) {
        console.error("Error:", err);
        setLoading(false);
      }
    };
    cateReq();
  }, []);

  // 如果还在加载，显示加载状态
  if (loading) {
    return <Spin />;
  }

  //翻页重新渲染
  const onchange = async (cur) => {
    setCurrent(cur);
    const res = await _categories([cur, 4]);
    const cateList = await res[0];
    setCateList(cateList);
  };

  //新增分类
  const onAdd = (e) => {
    setName(e);
    setIsModalOpen(true);
  };
  //确认新分类
  const handleOk = async () => {
    await _add({
      categoryName: `${name}`,
    });
    //重新渲染列表数据
    const res = await _categories([current, 4]);
    const cateList = res[0];
    setCateList(cateList);
    setIsModalOpen(false);
  };
  //取消新增
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //删除分类确认框
  const confirm = async (e) => {
    await _delete(e);
    message.success("删除成功");
    //重新渲染
    const res = await _categories([current, 4]);
    const cateList = res[0];
    setCateList(cateList);
  };
  const cancel = () => {
    message.error("取消删除");
  };

  return (
    <>
      <h1>分类管理</h1>
      <p>商品分类展示、新增分类、删除分类</p>
      <Button type="primary" onClick={onAdd} className="addBtn">
        新增分类
      </Button>
      <Modal
        title="请输入新分类："
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Input onChange={(e) => setName(e.target.value)} />
      </Modal>
      <table>
        <tbody>
          {cateList.map((item) => (
            <tr key={item.categoryId}>
              <td className="left-align">
                <h3>{item.categoryName}</h3>
                <p>共计{item.curToal}件商品</p>
              </td>
              <td className="right-align">
                <Popconfirm
                  title="删除："
                  description="确认删除此分类吗？"
                  onConfirm={() => confirm(item)}
                  onCancel={cancel}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button danger>删除分类</Button>
                </Popconfirm>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <Pagination
        align="end"
        onChange={(current) => onchange(current)}
        defaultCurrent={1}
        total={40}
        className="pages"
      />
    </>
  );
};

export default Products_control;
